// 文件上传
var {
  insertBlogList
} = require('../db/index')
var formidable = require('formidable')
exports.POEM = 'poem' // 古诗类
exports.POETRY = 'poetry'

const fs = require('fs')
async function dealUpload(ctx) {
  var form = new formidable.IncomingForm()
  form.keepExtensions = true
  form.uploadDir = __dirname + '/../static/blogs/'
  // 服务器端限制上传文件的大小
  form.maxFileSize = 100 * 1024
  form.parse(ctx.req, async (err, fields, files) => {
    if (err) {
      throw err
    }
    await fs.renameSync(files.file.path, form.uploadDir + files.file.name)
    // todo save to db
    insertBlogList(__dirname + "/../static/blogs/" + files.file.name, fields.title, fields.kind)
  })
  // 监听错误 - 图片上传大小过大，超过限制时触发
  form.on('error', function (e) {
    console.log(e)
    // other to do   
  })

}

// 验证cookie的有效期，即验证登陆状态
const valiateCookie = function(ctx, next) {
  // return next()
  if (!(ctx.cookies.get('LoginStatus')) 
  && ctx.url != '/login' 
  && ctx.url != '/register') {
    ctx.redirect('/login')
  } else {
    console.log('LoginStatus', ctx.cookies.get('LoginStatus'))
    return next()
  }
}

module.exports = {dealUpload, valiateCookie}